﻿'use strict';

const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('【updateTaskProgress】云函数被调用，event：', event);
  
  const { taskId, progressStep, progressText, userId } = event;
  
  if (!taskId || !progressStep || !userId) {
    return {
      code: 400,
      msg: '缺少必要参数',
      data: null
    };
  }
  
  try {
    // 更新任务进度
    const collection = db.collection('taskList');
    const updateResult = await collection.doc(taskId).update({
      progress_step: progressStep,
      progress_text: progressText || '',
      latest_update: progressText || '进度已更新',
      update_time: new Date()
    });
    
    console.log('【updateTaskProgress】任务进度更新结果：', updateResult);
    
    if (updateResult.updated > 0) {
      // 获取任务详情，用于生成通知
      const taskResult = await collection.doc(taskId).get();
      if (taskResult.data && taskResult.data.length > 0) {
        const task = taskResult.data[0];
        
        // 为任务发布者生成进度更新通知
        if (task.publisher_id && task.publisher_id !== userId) {
          await uniCloud.callFunction({
            name: 'createTaskNotification',
            data: {
              userId: task.publisher_id,
              taskId: taskId,
              taskTitle: task.title || task.type,
              status: 'progress_update',
              actionUserId: userId,
              actionUserNickname: task.receiver_name || '接单者',
              progressText: progressText || '进度已更新'
            }
          });
          console.log('【updateTaskProgress】进度更新通知生成成功');
        }
      }
      
      return {
        code: 200,
        msg: '任务进度更新成功',
        data: {
          progressStep: progressStep,
          progressText: progressText,
          updateTime: new Date()
        }
      };
    } else {
      return {
        code: 404,
        msg: '任务不存在或更新失败',
        data: null
      };
    }
    
  } catch (error) {
    console.error('【updateTaskProgress】异常:', error);
    return {
      code: 500,
      msg: '更新任务进度失败：' + error.message,
      data: null
    };
  }
};
